package com.xuzimian.demo.aws.cloud.s3;


import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.nio.file.Paths;

public class AmazonS3ClientDemo {

    public static void main(String[] args) throws URISyntaxException, FileNotFoundException {
        s3UseCredentialDemo();
    }

    private static void testWebIdentityTokenFileCredentialsProvider() {
        Region region = Region.US_EAST_2;

        S3Client s3 = S3Client.builder()
                .region(region)
                .credentialsProvider(WebIdentityTokenFileCredentialsProvider.create())
                .build();
        String bucket = "swgen-file";

        ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build();
        ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest);
        listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name()));
    }

    private static void s3UseCredentialDemo() {
        Region region = Region.US_EAST_2;

        ProfileCredentialsProvider profileCredentialsProvider = ProfileCredentialsProvider.builder()
                .profileFile(ProfileFile.builder()
                        .type(ProfileFile.Type.CREDENTIALS)
                        .content(Paths.get("/Users/zimian.xu/.aws/credentials"))
                        .build())
                .build();

        S3Client s3 = S3Client.builder()
                .region(region)
                .credentialsProvider(profileCredentialsProvider)
                .build();

        String bucket = "swgen-file";

        ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build();
        ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest);
        listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name()));

    }

    private static void UploadFileTest(S3Client s3, String bucket) {
        PutObjectResponse putObjectResponse = s3.putObject(PutObjectRequest.builder().bucket(bucket).key("test1.jpg")
                        .build(),
                RequestBody.fromFile(new File(AmazonS3ClientDemo.class.getResource("/runtime_class_load.png").getFile()))
        );

        System.out.println(putObjectResponse);
    }
}
